/*
 * version: 0.1 CopyRight (C) yyc
 * author: yyc
 * email: lzuyao@163.com
 * date: 2013-11-27
 */

package ant.colony.algorithm;

import java.util.HashMap;
import java.util.Map;

/**
 * The Roulette class simulate the roulette wheel game. 
 * A target in the form of <id, value> is a goal on the wheel, 
 * witch you can get randomly. Each target on the roulette wheel
 * can be returned by wheel() method with a probability affected 
 * by value. If the value of a target is larger compared with 
 * other targets, then this target has a high probability to be 
 * returned.
 * @author yyc
 */
public class Roulette {
    
	HashMap<Integer, Double> map;
	double sum = 0.0;

	//
	public Roulette(){
		map = new HashMap<>();
	}
	public Roulette(int targetNum) {
		map = new HashMap<>(targetNum);
	}

	/**
	 * Add a new target <id, value> to the roulette, if the id is already
	 * existed the old one will be replaced.
	 * 
	 * @param id
	 * @param value
	 */
	public void addTarget(int id, double value) {
		// if(map.containsKey(id));
		if (value < 0)
			return;
		map.put(id, value);
		sum += value;
	}

	/**
	 * Clear all targets.
	 */
	public void clearAllTarget() {
		map.clear();
	}

	/**
	 * This method run the roulette and get the id of a value with probability
	 * (value/sum)
	 * 
	 * @return the id of the value.
	 */
	public int wheel() {
		double t = Math.random() * sum;
		int ret = 0;

		double s = 0.0;
		for (Map.Entry<Integer, Double> entry : map.entrySet()) {
			s += entry.getValue();// record the current mark
			if (t < s) {
				ret = entry.getKey();
				break;
			}
		}
		return ret;
	}

	public int getTargetNumber(){
		return map.size();
	}
}
